/*
 * The MiniQt Library
 *
 * Copyright (C) 1999 Sandro Sigala <ssigala@globalnet.it>
 */

/*
 * A quick and dirty implementation of a string class.
 * Warning: the null character is used for terminating the
 * data!
 */

#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "qstring.h"

QString::QString()
{
	datalen = 0;
	initData(16);
	data[0] = '\0';
}

QString::QString(const QString& copy)
{
	datalen = copy.datalen;
	initData(copy.datalen + 1);
	strcpy(data, copy.data);
}

QString::QString(const char *copy)
{
	datalen = strlen(copy);
	initData(datalen + 1);
	strcpy(data, copy);
}

QString::~QString()
{
	delete [] data;
}

size_t QString::length()
{
	return datalen;
}

size_t QString::size()
{
	return datalen;
}

const char *QString::c_str() const
{
	return data;
}

QString::operator const char *() const
{
	return data;
}

QString& QString::sprintf(const char *fmt, ...)
{
	char buf[1024];

	va_list ap;
	va_start(ap, fmt);
	vsprintf(buf, fmt, ap);
	this->operator =(buf);
	va_end(ap);

	return *this;
}

QString& QString::operator =(const QString& copy)
{
	delete [] data;
	datalen = copy.datalen;
	initData(copy.datalen + 1);
	strcpy(data, copy.data);
	return *this;
}

QString& QString::operator +=(const QString& copy)
{
	char *olddata = data;
	datalen = datalen + copy.datalen;
	initData(datalen + 1);
	strcpy(data, olddata);
	strcat(data, copy.data);
	delete [] olddata;
	return *this;
}

void QString::initData(size_t size)
{
	datamaxlen = size;
	data = new char[size];
}

QString operator +(const QString& s1, const QString& s2)
{
	QString s(s1);
	s += s2;
	return s;
}

QString operator +(const char *s1, const QString& s2)
{
	QString s(s1);
	s += s2;
	return s;
}

QString operator +(const QString& s1, const char *s2)
{
	QString s(s1);
	s += s2;
	return s;
}

bool operator ==(const QString& s1, const QString& s2)
{
	return !strcmp(s1, s2);
}

bool operator ==(const char *s1, const QString& s2)
{
	return !strcmp(s1, s2);
}

bool operator ==(const QString& s1, const char *s2)
{
	return !strcmp(s1, s2);
}
